<template>
  <el-container>
    <el-main>
      <el-form ref="productForm" :model="form" label-width="90px">
        <div style="display: flex">

          <el-form-item label="商品名称" style="width: 700px" prop="name" :rules="{ required: true, message: '请输入商品名称', trigger: 'blur' }">
            <el-input v-model="form.name" />
          </el-form-item>
        </div>
        <div style="display: flex">
          <!-- <el-form-item label="商品类型" prop="type" style="width: 300px" :rules="{ required: true, message: '请选择商品类型', trigger: 'blur' }">
            <el-cascader
              v-model="tempType"
              :disabled="typeDisabled"
              style="width: 100%;"
              :options="productTypeOptions"
              :props="{ expandTrigger: 'hover', value: 'id', label: 'name', children: 'childrens'}"
            />
          </el-form-item> -->
          <!-- <el-form-item label="商品类型" prop="type" style="width: 300px" :rules="{ required: true, message: '请选择商品类型', trigger: 'blur' }">
           <el-select v-model="form.type" placeholder="请选择" style="width:100%">
             <el-option label="实物商品" value="0"/>
             <el-option label="虚拟商品" value="1"/>
           </el-select>
         </el-form-item> -->

          <el-form-item label="商品分类" style="width: 400px" prop="productCategoryId" :rules="{ required: true, message: '请选择商品分类', trigger: 'blur' }">
            <!-- <el-input v-model="categoryName" suffix-icon="el-icon-arrow-down" @focus="dialogShow" /> -->
            <el-cascader
              v-model="form.productCategoryId"
              style="width:100%"
              placeholder="请输入分类名"
              :options="productCategoryOptions"
              filterable
              clearable
              :show-all-levels="false"
              @change="productCategoryChange"
            />
          </el-form-item>

        </div>
        <div style="display: flex">

          <el-form-item label="商品来源" style="width: 300px">
            <el-select v-model="form.publishType" placeholder="请选择" style="width:100%">
              <el-option label="自营" :value="0" />
              <el-option label="联营" :value="1" />
            </el-select>
          </el-form-item>

          <el-form-item label="主供应商" style="width: 400px" :rules="{ required: true, message: '请输入商品名称', trigger: 'blur' }" prop="supplierId">
            <!--可搜索带选择框-->
            <el-select
              v-model="supplierName"
              style="width:100%"
              filterable
              value-key="id"
              placeholder="请选择供应商关键字"
              :filter-method="searchSupp"
              :loading="suppLoading"
              @change="suppChange"
            >
              <el-option
                v-for="(item) in suppOptions"
                :key="item.id"
                :label="item.name"
                :value="item"
              />
              <el-option style="background-color: #f9f9f9;text-align: center;" label="--- 新增供应商 ---" value="#" />
            </el-select>
          </el-form-item>

        </div>
        <div style="display: flex">

          <el-form-item label="配送方式" prop="shippingMethod" style="width: 300px">
            <el-select v-model="form.shippingMethod" style="width: 100%" placeholder="请选择" multiple>
              <el-option
                v-for="(item,index) in shippingMethodList"
                :key="index"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="商品标签" style="width: 400px">
            <el-select v-model="tagIds" style="width: 100%" multiple placeholder="请选择">
              <el-option
                v-for="(item,index) in tagOptions"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </div>

        <el-tabs>
          <!--tab1-->
          <el-tab-pane label="SKU">
            <!--商品规格-->
            <!-- <div style="width: 100%;display: flex;justify-content: flex-end;align-items: center">
              <el-button type="primary" style="margin-bottom: 10px;" @click="addProduct" >添加规格</el-button>
            </div> -->
            <el-row style="display: flex; justify-content: flex-end; position: relative;;margin-left: 30px">
              <span class="el-icon-plus" style="position: absolute; top: -25px; left: 0px; color: #409EFF;" @click="addProduct" />
              <el-col :span="23">
                <el-table
                  :data="productList"
                  border
                  stripe
                >
                  <el-table-column
                    label="货号/条码"
                    width="120"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.sn" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="商品图片"
                    width="80"
                    align="center"
                  >
                    <template slot-scope="{row}">
                      <single-upload v-model="row.thumbnail" list-type="picture-card" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="规格"
                    min-width="120"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.spec1" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="颜色"
                    min-width="85"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.spec2" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="单位"
                    width="70"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.unit" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="单位类型"
                    width="110"
                  >
                    <template slot-scope="{row}">
                      <el-select v-model="row.unitType" placeholder="请选择" :disabled="row.isChose" @change="chooseUnitType(row.length)">
                        <el-option label="不启用" :value="0" :disabled="row.isClick" />
                        <el-option label="最小单位" :value="1" :disabled="row.isClick" />
                        <el-option label="统计单位" :value="2" :disabled="row.isCount||row.isFirst" />
                        <el-option label="辅助单位" :value="3" :disabled="row.isFirst" />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="转换系数"
                    width="80"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.unitRate" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="库存"
                    width="80"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.stock" type="number" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="积分"
                    width="85"
                    v-if="tempType == 12"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.point" type="number" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="市场价"
                    width="85"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.marketPrice" type="number" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="销售价"
                    width="85"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.price" type="number" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="成本价"
                    width="85"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.cost" type="number" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="vips.length>0"
                    :label="vips[0].name"
                    width="85"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.vip1price" type="number" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="vips.length>1"
                    :label="vips[1].name"
                    width="85"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.vip2price" type="number" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="vips.length>2"
                    :label="vips[2].name"
                    width="85"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.vip3price" type="number" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="vips.length>3"
                    :label="vips[3].name"
                    width="85"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.vip4price" type="number" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="vips.length>4"
                    :label="vips[4].name"
                    width="85"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.vip5price" type="number" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    fixed="right"
                    align="center"
                    label="操作"
                    width="80"
                  >
                    <template v-if="!row.isList" slot-scope="{row}">
                      <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                        <a @click="delProduct(row)">
                          <i style="color: #F56C6C" class="el-icon-delete" />
                        </a>
                      </el-tooltip>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
            </el-row>
          </el-tab-pane>
          <!--tab2-->
          <el-tab-pane label="销售">
            <div style="display: flex">
              <el-form-item label="分销策略" style="width: 300px">
                <el-select v-model="form.distributionId" style="width: 100%" placeholder="请选择">
                  <el-option
                    v-for="(item,index) in disOptions"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="品牌类型" style="width: 300px">
                <!--可搜索带选择框-->
                <el-select
                  v-model="form.brandId"
                  style="width:100%"
                  filterable
                  placeholder="请选择品牌关键字"
                  :filter-method="searchBrand"
                  :loading="brandLoading"
                  @change="brandChange"
                >
                  <el-option
                    v-for="item in barrelOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                  <el-option style="background-color: #f9f9f9;text-align: center;" label="--- 新增品牌 ---" value="#" />
                </el-select>
              </el-form-item>

            </div>
            <div style="display: flex">
              <el-form-item label="最小订购量" style="width: 300px">
                <el-input v-model="form.minLimit" type="number" @mousewheel.native.prevent />
              </el-form-item>
              <el-form-item label="最大日限量" style="width: 300px">
                <el-input v-model="form.maxLimit" type="number" />
              </el-form-item>
            </div>
            <div style="display: flex">
              <el-form-item label="运费模板" style="width: 300px">
                <!--可搜索带选择框-->
                <el-select
                  v-model="form.freightId"
                  style="width:100%"
                  filterable
                  clearable
                  placeholder="请选择运费键字"

                  :filter-method="searchFreight"
                  :loading="freightLoading"
                  @change="freightChange"
                >
                  <el-option
                    v-for="item in freightNames"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                  <el-option style="background-color: #f9f9f9;text-align: center;" label="--- 新增运费 ---" value="/" />
                </el-select>
              </el-form-item>
              <div>
                <el-form-item label="重量(Kg)" style="width: 300px">
                  <el-input v-model="form.weight" type="number" @mousewheel.native.prevent />
                </el-form-item>
              </div>
            </div>
<!--            <div>-->
<!--              <el-form-item label="属性标签" style="width: 300px">-->
<!--                <el-input v-model="article.productMeta.label" placeholder="例如:辛辣,微酸" />-->
<!--              </el-form-item>-->
<!--            </div>-->
            <div>
              <el-form-item label="保质期(天)" style="width: 300px">
                <el-input v-model="form.quality" type="number" @mousewheel.native.prevent />
              </el-form-item>
            </div>
            <div style="display: flex">

              <el-form-item label="商品简介" style="width: 600px">
                <el-input v-model="form.subTitle" placeholder="在商品以副标题形式展示" />
              </el-form-item>

            </div>

          </el-tab-pane>
          <!--tab3-->
          <!-- <el-tab-pane label="清单">
            <el-row style="display: flex; justify-content: flex-end; position: relative;margin-left: 30px">
              <span class="el-icon-circle-plus-outline" style="position: absolute; left: 0px; top: 66px; color: #409EFF;" @click="addProps" />
              <el-col :span="23">
                <el-table
                  :data="article.productMeta.props"
                  border
                  stripe
                  style="width:600px;"
                >
                  <el-table-column
                    label="名称"
                    min-width="85"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.name" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="说明"
                    min-width="85"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.memo" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="参数"
                    min-width="85"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.params" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="操作"
                    width="80"
                  >
                    <template  slot-scope="scope" v-if="scope.$index!=0">
                      <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                        <a @click="delProps(scope)">
                          <i style="color: #F56C6C" class="el-icon-delete" />
                        </a>
                      </el-tooltip>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>

            </el-row>


          </el-tab-pane> -->
          <el-tab-pane label="详情">
            <div class="menu-wrapper">
              <tinymce v-model="article.content" :height="300" :width="950" />
              <!-- <el-row>
                <div class="photo-content">
                  <div style="margin-top: 20px">
                    <span style="font-size: 18px;color:#409EFF;">轮播图</span>
                  </div>
                </div>
                <el-col :span="15">
                  <multi-upload v-model="article.productMeta.images" />
                </el-col>
              </el-row> -->

              <el-row>
                <div class="photo-content">
                  <div style="margin-top: 20px">
                    <span style="font-size: 18px;color:#409EFF;">轮播图(最多五张)</span>
                  </div>
                </div>
                <el-col :span="15">
                  <multiUploadDraggable v-model="article.productMeta.images" />
                </el-col>
              </el-row>

              <el-row>
                <div class="photo-content">
                  <div style="margin-top: 20px;">
                    <span style="font-size: 18px;color:#409EFF;margin: 10px 0;">视频介绍</span>
                  </div>
                </div>
                <el-col :span="8">
                  <video-upload v-model="article.productMeta.video" />
                </el-col>
              </el-row>
            </div>
          </el-tab-pane>
        </el-tabs>
        <el-form-item>
          <el-button style="margin-top: 30px" type="primary" :loading="clicked" @click="editProduct('productForm')">
            &nbsp&nbsp完 成&nbsp&nbsp
          </el-button>
        </el-form-item>

      </el-form>
      <category-dialog ref="categoryDialog" request="productCategory" @confirm="categoryDialogConfirm" />

      <el-dialog
        v-el-drag-dialog
        title="添加品牌"
        :visible.sync="brandVisible"
        width="50%"
        :before-close="brandClose"
      >
        <div style="height: 70vh;overflow: auto;position: relative;">
          <brandAdd :is-dialog="true" @confirm="brandAddConfirm" />
        </div>
      </el-dialog>
      <el-dialog
        v-el-drag-dialog
        title="添加供应商"
        :visible.sync="suppVisible"
        width="50%"
        :before-close="suppClose"
      >
        <div style="height: 70vh;overflow: auto;position: relative;">
          <suppAdd :is-dialog="true" @confirm="suppAddConfirm" />
        </div>
      </el-dialog>
      <addFreight ref="freight" />
    </el-main>
  </el-container>
</template>
<style lang="scss" scoped>
  .photo-content{
    width: 100%;
    display: flex;
    align-items: flex-end;
    border-top: 1px #eee solid;
    margin-bottom: 20px;
    margin-top: 10px;
  }
  /deep/.el-input__inner{
    padding: 0 5px;
  }
  /deep/ .el-upload--picture-card{
    width: 50px !important;
    height: 50px !important;
    line-height: 50px !important;
    text-align: center;
    .menu-wrapper {
      margin: 15px;
    }
  }
</style>
<script>
import { list as vipList } from '@/api/vip'
import permission from '@/directive/permission/index.js' // 权限判断指令
import MultiUpload from '@/components/Upload/multiUpload'
import multiUploadDraggable from '@/components/Upload/multiUploadDraggable'

import VideoUpload from '@/components/Upload/videoUpload'
import Tinymce from '@/components/Tinymce'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import { EventBus } from '@/api/eventBus'
import utils from '../../utils/utils.js'
import { list as freightList } from '@/api/freight'
import { find, update } from '@/api/product'
import { find as findInfo, update as updateInfo } from '@/api/productArticle'
import { list as tagList } from '@/api/tag'
import { list as brandList } from '@/api/brand'
import { list as suppList } from '@/api/supplier'
import { list as productCategoryList } from '@/api/productCategory'
import CategoryDialog from '@/components/CategoryDialog'
import SingleUpload from '@/components/Upload/singleUpload'
import brandAdd from '../brand/add.vue'
import suppAdd from '../supplier/add.vue'
import addFreight from '../freight/add'
import { list as distributionList } from '@/api/distribution.js'
import { getMenuTree as MenuTree } from '@/api/sysMch'
export default {
  name: 'product-edit',
  directives: { elDragDialog, permission },
  filters: {},
  components: {
    CategoryDialog, SingleUpload, brandAdd, suppAdd, MultiUpload, VideoUpload, Tinymce, addFreight, multiUploadDraggable
  },
  data() {
    return {
      id: '',
      vips: [],
      length: 0,
      times: null,
      isCount: true,
      shippingMethods: [],
      productCategoryOptions: [],
      clicked: false, // 按钮防双击
      categoryName: '',
      subscribe: false,
      market: false,
      shippingMethodList: [
        { name: '普通快递', value: '0' },
        { name: '到店提货', value: '1' },
        { name: '同城配送', value: '2' }
      ],
    
      typeDisabled: false,
      productTypeOptions: [
        {
          id: 10, name: '实物商品',
          childrens: [
            { id: 20, name: '普通商品' }
          ]
        },
        {
          id: 11, name: '虚拟商品',
          childrens: [
            { id: 20, name: '商品' },
            { id: 21, name: '套餐' }
          ]
        },
        {
          id: 12, name: '积分商品',
        }
      ],
      article: {
        id: '',
        goods: '',
        productMeta: {
          props:[],
          images: [],
          video: ''
        },
        content: ''
      },
      form: {
        maxLimit: '',
        publishType: 0,
        id: '',
        name: '',
        productCategoryId: '',
        shortName: '',
        orders: '',
        type: '0',
        freightId: '',
        shippingMethod: [],
        isMarketable: false,
        subTitle: '',
        minLimit: '',
        // labal: '',
        quality: '',
        distributionId: '',
        brandId: '',
        stock: '',
        supplierId: '',
        allocatedStock: '',
        weight: '',
        goodsId: ''
      },
      tagIds: [],
      disOptions: [],
      tagOptions: [],
      freightNames: [],
      brandLoading: false,
      freightLoading: false,
      brandVisible: false,
      barrelOptions: [],
      suppOptions: [],
      suppLoading: false,
      suppVisible: false,
      supplierName: '',
      brandName: '',
      productList: [
        {
          isClick: false,
          isFirst: true,
          maxLimit: '',
          length: 0,
          publishType: 0,
          isList: true,
          name: '',
          productCategoryId: '',
          shortName: '',
          orders: 0,
          type: '0',
          freightId: '',
          isMarketable: false,
          subTitle: '',
          minLimit: '',
          // labal: '',
          quality: '',
          isChose: false,
          isCount: false,
          distributionId: '',
          brandId: '',
          stock: '',
          supplierId: '',
          allocatedStock: '',
          weight: '',
          subType: 0,
          shippingMethod: '',
          // ------
          sn: '',
          thumbnail: '',
          spec1: '',
          spec2: '',
          unit: '',
          unitRate: '',
          marketPrice: '',
          price: '',
          cost: '',
          point:'',
          unitType: '',
          vip1price: '',
          vip2price: '',
          vip3price: '',
          vip4price: '',
          vip5price: '',
          article: {
            productMeta: {
              images: [],
              video: '',
              props:[],
            },
            content: ''
          }
        }
      ]
    }
  },
  watch: { // 路由地址不变的情况下,如果id变化则重新获取数据
    $route(newVal, oldVal) {
      console.log(newVal)
      if (newVal.name == 'product-edit' && newVal.query.id != this.id) {
        this.getFindData()
      }
    }
  },
  created() {
    EventBus.$on('freight-add', res => { // 监听新增完毕
      // 更新列表数组
      this.freightNames.splice(0, 0, res)
    })
    this.loadMenuTree()
    this.loadVip()
    this.loadFright('')
    this.loadTag()
    this.loadBrand('')
    this.loadSupp('')
    this.loadDistribution()
    this.getFindData()
    this.loadProductCategory()
  },
  activated() {
  },
  methods: {
    delProps(scope){
      this.article.productMeta.props.splice(scope.$index,1)

    },
    loadMenuTree() {
      MenuTree().then(res => {
        res.data.forEach(list => {
          if (list.permission == 'product.list') {
            list.childrens.forEach(item => {
              if (item.permission == 'emptyBarrel-list') {
                this.productTypeOptions[0].childrens.push({ id: 24, name: '管理空桶' })
                this.productTypeOptions[1].childrens.push({ id: 23, name: '押金' })
              } else if (item.permission == 'waterTicket-list') {
                this.productTypeOptions[1].childrens.push({ id: 22, name: '水票' })
              }
            })
          }
        })
      }).catch(err => { console.log(err) })
    },
    addProps(){
      var form={
        name:'',
        memo:'',
        params:''
      }
      this.article.productMeta.props.push(form)
      // this.setAddPropskHeight()
    },
    getFindData() {
      this.times = new Date().getSeconds()
      this.id = this.$route.query.id
      var _this = this
      find(this.id).then(response => {
        console.log(response)
        _this.article = response.data.article
        _this.length = response.data.products.length - 1
        for (var k = 0; k < response.data.products.length; k++) {
          this.length = k
          response.data.products[k]['length'] = this.length
        }
        for (var i = 1; i < response.data.products.length; i++) {
          if (response.data.products[i].unitType == 2) {
            response.data.products[i]['isCount'] = false
          } else {
            response.data.products[i]['isCount'] = true
          }
          if (response.data.products[0].unitType == 0) {
            response.data.products[i]['isClick'] = true
            response.data.products[i]['isChose'] = true
          } else {
            response.data.products[i]['isClick'] = false
            response.data.products[i]['isChose'] = false
          }
        }

        response.data.products[0]['isFirst'] = true

        _this.productList = response.data.products
        _this.tagIds = []
        if (!utils.isNull(this.productList[0].tags)) {
          _this.productList[0].tags.forEach(function(item) {
            _this.tagIds.push(item.id)
          })
        }

        this.productList.forEach((item) => {
          if (item.isList) {
            this.form.maxLimit = item.maxLimit
            this.form.id = item.id
            this.form.name = item.name
            this.categoryName = item.productCategoryName
            this.form.productCategoryId = item.productCategoryId
            this.form.shortName = item.shortName
            this.form.orders = item.orders
            this.form.publishType = item.publishType
            // this.form.type = JSON.stringify(item.type);
            if (item.subType == 2) {
              this.typeDisabled = true
            }
            if (item.type== 2) {
              this.tempType = [item.type + 10]
            }else {
              this.tempType = [item.type + 10, item.subType + 20]
            }
            this.form.isMarketable = item.isMarketable
            this.form.subTitle = item.subTitle
            this.form.minLimit = item.minLimit
            // this.form.labal = item.labal;
            this.form.quality = item.quality
            this.form.distributionId = item.distributionId
            this.form.brandId = item.brandId
            this.form.stock = item.stock
            this.form.supplierId = JSON.stringify(item.supplierId)
            this.form.allocatedStock = item.allocatedStock
            this.form.weight = item.weight
            this.form.goodsId = item.goodsId
            this.form.freightId = item.freightId
            if (item.shippingMethod) {
              if (!utils.isNull(item.shippingMethod)) {
                _this.form.shippingMethod = item.shippingMethod.split(',')
              } else {
                _this.form.shippingMethod = ['0']
              }
            } else {
              _this.form.shippingMethod = ['0']
            }
          }
        })
        this.supplierName = response.data.supplierName
        this.brandName = response.data.brandName
        console.log(_this.form)
      }).catch(error => {
        console.log(error.content)
      })
    },
    loadDistribution() {
      distributionList().then(res => {
        this.disOptions = res.data.data
      }).catch(err => {
        console.log(err)
      })
    },
    // 商品分类选择事件
    productCategoryChange(val) {
      this.form.productCategoryId = val[val.length - 1]
    },
    // 加载商品分类的数据
    loadProductCategory() {
      productCategoryList().then(response => {
        this.productCategoryOptions = this.formatProductCategoryData(response.data)
      }).catch(error => {
      })
    },
    // 整理商品分类数据
    formatProductCategoryData(data) {
      const _this = this
      const productCategoryOptions = []
      if (data.length > 0) {
        data.map(item => {
          const productCategoryOptionsItem = {}
          productCategoryOptionsItem.value = item.id
          productCategoryOptionsItem.label = item.name
          if (item.childrens.length > 0) {
            productCategoryOptionsItem.children = _this.formatProductCategoryData(item.childrens)
          }
          productCategoryOptions.push(productCategoryOptionsItem)
        })
      }
      return productCategoryOptions
    },
    loadVip() {
      vipList().then(res => {
        res.data.data.forEach(item=>{
          if (item.vip>0){
            this.vips.push(item)
          }
        })
        this.vips = this.vips.sort(this.compare('vip', true))
      })
    },
    compare(property, desc) {
      return function(a, b) {
        var value1 = a[property]
        var value2 = b[property]
        if (desc == true) {
          // 升序排列
          return value1 - value2
        } else {
          // 降序排列
          return value2 - value1
        }
      }
    },
    loadFright(query) {
      const params = new URLSearchParams()
      params.append('name', query)
      params.append('pageNum', 1)
      params.append('pageSize', 1000)
      this.freightLoading = true
      freightList(params).then(response => {
        this.freightLoading = false
        this.freightNames = response.data.data
      }).catch(error => {
        this.freightLoading = false
      })
    },
    searchFreight(query) {
      if (query.length < 2) {
        this.$message.error('不得少于两个字符')
        return
      }
      this.loadFright(query)
    },
    loadTag() {
      const _this = this
      const params = new URLSearchParams()
      params.append('pageNum', 1)
      params.append('pageSize', 1000)
      params.append('type', 3)
      tagList(params).then(response => {
        console.log(response)
        _this.tagOptions = response.data.data
      }).catch(error => {
      })
    },
    dialogShow() {
      console.log('点击了')
      this.$refs.categoryDialog.show()
    },
    categoryDialogConfirm(val) {
      this.form.productCategoryId = val.id
      this.categoryName = val.name
    },
    freightChange(val) {
      if (val == '/') {
        this.form.freightId = ''
        this.$refs.freight.dialogFormVisible = true
        this.$refs.freight.addFreightClick()
      }
    },
    loadBrand(query) {
      const params = new URLSearchParams()
      params.append('pageNum', 1)
      params.append('pageSize', 50)
      params.append('name', query)
      this.brandLoading = true
      brandList(params).then(response => {
        console.log(response)
        this.brandLoading = false
        this.barrelOptions = response.data.data
        this.setAddClickHeight()
      }).catch(error => {
        this.brandLoading = false
      })
    },
    searchBrand(query) {
      if (query.length < 2) {
        this.$message.error('不得少于两个字符')
        return
      }
      this.loadBrand(query)
    },
    brandChange(val) {
      if (val == '#') {
        this.form.brandId = ''
        this.brandVisible = true
      } else {
        this.form.brandId = val
      }
    },
    brandClose() {
      this.brandVisible = false
    },
    brandAddConfirm(val) {
      this.barrelOptions.push(val)
      this.form.brandId = val.id
      this.brandVisible = false
    },
    loadSupp(query) {
      const params = new URLSearchParams()
      params.append('pageNum', 1)
      params.append('pageSize', 10)
      params.append('name', query)
      this.suppLoading = true
      suppList(params).then(response => {
        console.log(response)
        this.suppLoading = false
        this.suppOptions = response.data.data
      }).catch(error => {
        this.suppLoading = false
      })
    },
    suppChange(val) {
      console.log(val)
      if (val == '#') {
        this.form.supplierId = ''
        this.suppVisible = true
      } else {
        this.form.supplierId = val.id
      }
    },
    searchSupp(query) {
      if (query.length < 2) {
        this.$message.error('不得少于两个字符')
        return
      }
      this.loadSupp(query)
    },
    suppClose() {
      this.suppVisible = false
    },
    suppAddConfirm(val) {
      this.suppOptions.push(val)
      this.form.supplierId = val.id
      this.suppVisible = false
    },
    chooseUnitType(data) {
      if (this.productList.length > 1 && this.productList[0].unitType === 1) {
        if (this.productList[data].unitType === 2) {
          for (var l = 1; l < this.productList.length; l++) {
            this.productList[l].isCount = true
          }
          this.productList[data].isCount = false
          console.log(this.productList)
        } else {
          for (var v = 1; v < this.productList.length; v++) {
            this.productList[v].isCount = false
          }
        }
      }

      if (this.productList.length > 1) {
        if (this.productList[0].unitType == 0) {
          for (var i = 1; i < this.productList.length; i++) {
            this.productList[i].unitType = 0
            this.productList[i].isChose = true
          }
        } else {
          for (var i = 1; i < this.productList.length; i++) {
            this.productList[i].isChose = false
          }
        }
      }
    },
    addProduct() {
      this.length += 1
      this.productList.push({
        isList: false,
        name: '',
        isClick: true,
        productCategoryId: '',
        shortName: '',
        orders: 0,
        isFirst: false,
        length: this.length,
        type: '0',
        publishType: 0,
        isCount: this.isCount,
        isMarketable: false,
        subTitle: '',
        freightId: '',
        minLimit: '',
        maxLimit: '',
        // labal: '',
        quality: '',
        shippingMethod: '',
        distributionId: '',
        brandId: '',
        stock: '',
        supplierId: '',
        allocatedStock: '',
        weight: '',
        subType: '',
        // -----
        sn: this.productList[0].sn,
        thumbnail: this.productList[0].thumbnail,
        spec1: this.productList[0].spec1,
        spec2: this.productList[0].spec2,
        unit: this.productList[0].unit,
        unitRate: this.productList[0].unitRate,
        marketPrice: this.productList[0].marketPrice,
        price: this.productList[0].price,
        cost: this.productList[0].cost,
        unitType: '',
        vip1price: this.productList[0].vip1price,
        vip2price: this.productList[0].vip2price,
        vip3price: this.productList[0].vip3price,
        vip4price: this.productList[0].vip4price,
        vip5price: this.productList[0].vip5price,
        isChose: false,
        point: this.productList[0].point,
        article: {
          productMeta: {
            props:[],
            images: [],
            video: ''
          },
          content: ''
        }
      })
      if (this.productList.length > 1 && this.productList[0].unitType === 1) {
        for (var l = 1; l < this.productList.length; l++) {
          if (this.productList[l].unitType === 2) {
            this.productList[this.length].isCount = true
          }
        }
      }
      if (this.productList.length > 1) {
        if (this.productList[0].unitType === 0) {
          for (var i = 1; i < this.productList.length; i++) {
            this.productList[i].unitType = 0
            this.productList[i].isChose = true
          }
        }
      }
      this.setAddClickHeight()
    },
    delProduct(row) {
      var index = this.productList.indexOf(row)
      if (index !== -1) {
        this.productList.splice(index, 1)
      }
      this.setAddClickHeight()
    },
    editProduct(form) {
      const _this = this
      this.$refs[form].validate((valid) => {
        if (valid) { // 校验表单
          _this.clicked = true
          const params = new URLSearchParams()
          _this.tagIds.forEach(function(item) {
            params.append('tagIds', item)
          })
          if (this.productList[0].unitType != 0 && this.productList.length == 1) {
            _this.$message({
              message: '已启用多单位，商品规格不足',
              type: 'error'
            })
            _this.clicked = false
            return
          }
          for (let i = 0; i < _this.productList.length; i++) {
            delete this.productList[i].length
            if (this.productList[i].hasOwnProperty('isFirst')) {
              delete this.productList[i].isFirst
            }
            if (this.productList[i].hasOwnProperty('isChose')) {
              delete this.productList[i].isChose
            }
            if (this.productList[i].hasOwnProperty('isCount')) {
              delete this.productList[i].isCount
            }
            if (this.productList[i].hasOwnProperty('isClick')) {
              delete this.productList[i].isClick
            }
            _this.productList[i].name = _this.form.name
            _this.productList[i].productCategoryId = _this.form.productCategoryId
            _this.productList[i].shortName = _this.form.shortName
            _this.productList[i].orders = _this.form.orders
            // _this.productList[i].type = _this.form.type;
            // _this.productList[i].type = this.tempType
            _this.productList[i].type = this.tempType[0] - 10
            if (this.tempType.length > 1) {
              _this.productList[i].subType = this.tempType[1] - 20
            } else {
              _this.productList[i].subType = ''
            }
            if (this.tempType[0] - 10 == 2){
              _this.productList[i].subType == 0
            } else {
              _this.productList[i].subType = this.tempType[1] - 20
            }
            _this.productList[i].publishType = _this.form.publishType
            _this.productList[i].isMarketable = false
            _this.productList[i].freightId=_this.form.freightId
            _this.productList[i].subTitle = _this.form.subTitle
            _this.productList[i].minLimit = _this.form.minLimit
            _this.productList[i].maxLimit = _this.form.maxLimit
            _this.productList[i].quality = _this.form.quality
            _this.productList[i].distributionId = _this.form.distributionId
            _this.productList[i].brandId = _this.form.brandId
            // _this.productList[i].stock = _this.form.stock;
            _this.productList[i].supplierId = _this.form.supplierId
            _this.productList[i].allocatedStock = _this.form.allocatedStock
            _this.productList[i].weight = _this.form.weight
            _this.productList[i].goodsId = _this.form.goodsId
            _this.productList[i].article = _this.article
            _this.productList[i].shippingMethod = _this.form.shippingMethod.toString()
            if (parseInt(_this.productList[i].minLimit) != 0 && parseInt(_this.productList[i].maxLimit) != 0 && parseInt(_this.productList[i].minLimit) > parseInt(_this.productList[i].maxLimit)) {
              _this.$message({
                message: '最小订购量不可大于每日限量',
                type: 'success'
              })
              _this.clicked = false
              return
            }
            if (_this.productList[i].sn == '') {
              _this.$message({
                message: '请完善货号/条码',
                type: 'error'
              })
              _this.clicked = false
              return
            }
            if (utils.isNull(_this.productList[i].unit)) {
              _this.productList[i].unit = '件'
            }
            if (utils.isNull(_this.productList[i].unitRate)) {
              _this.productList[i].unitRate = 1
            }
            if (utils.isNull(_this.productList[i].thumbnail)) {
              _this.productList[i].thumbnail = 'http://cdn.rzico.com/weex/resources/images/defaultProduct.png'
            }
            if (utils.isNull(_this.productList[i].weight)) {
              _this.productList[i].weight = 0
            }
            if (utils.isNull(_this.productList[i].allocatedStock)) {
              _this.productList[i].allocatedStock = 0
            }
            if (utils.isNull(_this.productList[i].stock)) {
              _this.productList[i].stock = 0
            }
            if (utils.isNull(_this.productList[i].quality)) {
              _this.productList[i].quality = 0
            }
            if (utils.isNull(_this.productList[i].minLimit) || _this.productList[i].minLimit < 1) {
              _this.productList[i].minLimit = 1
            }
            if (utils.isNull(_this.productList[i].marketPrice)) {
              _this.productList[i].marketPrice = 0
            }
            if (utils.isNull(_this.productList[i].price)) {
              _this.productList[i].price = 0
            }
            if (utils.isNull(_this.productList[i].cost)) {
              _this.productList[i].cost = 0
            }
            if (utils.isNull(_this.productList[i].vip1price)) {
              _this.productList[i].vip1price = 0
            }
            if (utils.isNull(_this.productList[i].vip2price)) {
              _this.productList[i].vip2price = 0
            }
            if (utils.isNull(_this.productList[i].vip3price)) {
              _this.productList[i].vip3price = 0
            }
            if (utils.isNull(_this.productList[i].vip4price)) {
              _this.productList[i].vip4price = 0
            }
            if (utils.isNull(_this.productList[i].vip5price)) {
              _this.productList[i].vip5price = 0
            }
            if (utils.isNull(_this.productList[i].point)) {
              _this.productList[i].point = 0
            }
          }
          console.log(this.productList)
          update(_this.productList, params).then(response => {
            console.log(response)
            _this.clicked = false
            EventBus.$emit('product-edit', response.data[0])
            _this.$store.dispatch('tagsView/delView', _this.$route).then(({ visitedViews }) => {
              _this.$router.push({
                path: '/management/list'
              })
            })// 关闭当前tab回到列表
          }).catch(error => {
            _this.clicked = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    setAddClickHeight() {
      setTimeout(() => {
        // 获取表头的高度
        const tableTopHeight = document.querySelector('.el-table__header-wrapper').offsetHeight
        // 获取一行表格高度
        const tableHeight = document.querySelector('.el-table__row').offsetHeight
        // 获取添加按钮样式
        const addClickStyle = document.querySelector('.el-icon-plus')
        // 获取添加按钮高度
        const addClickHeight = addClickStyle.offsetHeight
        // 设置添加按钮的位置
        const moveHeight = tableTopHeight + ((this.productList.length - 1) * tableHeight) + ((tableHeight - addClickHeight) / 2)
        addClickStyle.style.top = moveHeight + 'px'
      }, 100)
    }
  }
}
</script>
